package edu.sctu.wangxiaoqiang.day20150625;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by user25 on 2015/6/26.
 */
public class Json {

    public static String createJsonString(String key, Object value)
    {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key, value);
        return jsonObject.toString();
    }

   /*
    2、获取javaBean
     */
    public Person getPerson(String jsonStr)
    {
        Person person = new Person();
        try
        {// 将json字符串转换为json对象
            JSONObject jsonObj = new JSONObject(Boolean.parseBoolean(jsonStr));
            // 得到指定json key对象的value对象
            JSONObject personObj = jsonObj.getJSONObject("person");
            // 获取之对象的所有属性
            person.setId(personObj.getInteger("id"));
            person.setName(personObj.getString("name"));
            person.setAddress(personObj.getString("address"));
        }
        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return person;
    }

    public List<Person> getPersons(String jsonStr)
    {
        List<Person> list = new ArrayList<Person>();

        JSONObject jsonObj;
        try
        {// 将json字符串转换为json对象
            jsonObj = new JSONObject(Boolean.parseBoolean(jsonStr));
            // 得到指定json key对象的value对象
            JSONArray personList = jsonObj.getJSONArray("persons");
            // 遍历jsonArray
            for (int i = 0; i < personList.size(); i++)
            {
                // 获取每一个json对象
                JSONObject jsonItem = personList.getJSONObject(i);
                // 获取每一个json对象的值
                Person person = new Person();
                person.setId(jsonItem.getInteger("id"));
                person.setName(jsonItem.getString("name"));
                person.setAddress(jsonItem.getString("address"));
                list.add(person);
            }
        }
        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return list;
    }
}
